package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.entry.Emil;
import com.oa.android.entry.Fjian;
import com.oa.android.entry.GGao;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;


/**
 *
 * 公告详情
 * @author -zouqh
 * 
 */
public class DetailsGGaoActivity extends Activity implements OnClickListener {

	private ImageView close;
	private TextView title,emilTitle,tiem,form,content,rightText;
	private MyGridView gridView;
	private GGao emil;
	private String[] fuj;
	private FujAdapter adapter;
	private ScrollView myScrollView;
	private ProgressDialog progressDialog;
	private Dialog Jdialog;
	List<Fjian> list;
	public static DetailsGGaoActivity activity;

	private   String filePath = Environment.getExternalStorageDirectory().getPath() + File.separator+"ZHOA"+ File.separator;
	private String redStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		activity=this;
		emil= (GGao) getIntent().getSerializableExtra("ggao");
		setContentView(R.layout.details_ggao_activity);
		close = (ImageView) findViewById(R.id.close);
		title = (TextView) findViewById(R.id.title_text);
		emilTitle= (TextView) findViewById(R.id.emilTitle);
		rightText= (TextView) findViewById(R.id.ritgh_text);
		tiem= (TextView) findViewById(R.id.time);
		form= (TextView) findViewById(R.id.form);
		content= (TextView) findViewById(R.id.emilContent);
		gridView=(MyGridView)findViewById(R.id.gridview);
		myScrollView = (ScrollView)findViewById(R.id.myScrollView);
		myScrollView.smoothScrollTo(0, 20);
		if (emil.getZT().equals("0")){
			yesRead();
		}
//		yesRead();
		System.out.print("AAAAAAA"+emil);
		getFj();
		title.setText("公告详情");
		rightText.setText("编辑");
		close.setOnClickListener(this);
		if(emil.getOPEMP().equals(UConstants.EmpId)){
			rightText.setVisibility(View.VISIBLE);
		}

		rightText.setOnClickListener(this);
		if (emil!=null){
			emilTitle.setText(emil.getTITLE());
			if (Util.NoNull(emil.getLX())){
				if (emil.getLX().equals("D")){
					form.setText("发布人："+emil.getEMPNAME()+"    单位公告");
				}else{
					form.setText("发布人："+emil.getEMPNAME()+"    内部公告");
				}
			}else{
				form.setText("发布人："+emil.getEMPNAME());
			}

			content.setText(Html.fromHtml(emil.getCONTENT()));
			tiem.setText("时间："+emil.getOPTIME());
//			if (Util.NoNull(emil.getFUJIAN())){
//				if (emil.getFUJIAN().contains("|")){
//					fuj=emil.getFUJIAN().split("\\|");
//				}else{
//					fuj=new String[]{emil.getFUJIAN()};
//				}
//				adapter=new FujAdapter(this,fuj);
//				gridView.setAdapter(adapter);
//
//			}
		}

		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.i("position===",""+position);
				if (!new File(filePath+list.get(position).getOLDNAME()).exists()){

					if (Util.NoNull(list.get(position).getNOWNAME())){

					String[] bs= list.get(position).getNOWNAME().split("/");
					StringBuffer brf = new StringBuffer();
					for (int i = 0; i < bs.length; i++) {
						if(i==bs.length-1){

							try {
								brf.append(URLEncoder.encode(bs[i],"UTF-8").replaceAll("\\+", "%20"));//去空格
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}else {
							brf.append(bs[i]).append("/");
						}

					}

					pointDialog("您需要下载此文件吗？",1,brf.toString(),list.get(position).getOLDNAME());
					}else{
						Toast.makeText(DetailsGGaoActivity.this,"下载地址有误",Toast.LENGTH_SHORT).show();
					}
//					downloadFile(UConstants.URL_DOWN+fuj[position],filePath+fuj[position]);
				}else{
					pointDialog("您需要打开此文件吗？",0,list.get(position).getOLDNAME(),list.get(position).getOLDNAME());
//					openFile(new File(filePath+fuj[position]));
				}

			}
		});

	}

	public void setViewUI(String tile,String con){
		emilTitle.setText(tile);
		content.setText(con);
		GGaoActivity.gGaoActivity.setResh();

	}

	private Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (Util.NoNull(redStr)&&redStr.length()>0){
				System.out.println("redStr==="+redStr);
				try {
					JSONObject object = new JSONObject(redStr);

					boolean success = object.getBoolean("success");
//
					if (success) {

						GGaoActivity.gGaoActivity.setResh();


					}
//
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent ;
		switch (v.getId()) {
		case R.id.close:
			finish();
			break;
			case R.id.ritgh_text:
				intent=new Intent(this,EditAllActivity.class);
				intent.putExtra("id",emil.getID());
				intent.putExtra("title",emil.getTITLE());
				intent.putExtra("content",emil.getCONTENT());
				intent.putExtra("type","1");
				startActivity(intent);
				break;

		default:
			break;
		}
	}

	/**
	 * 提示
	 */
	private void pointDialog(String str, final int p, final String pat,final  String odfile) {
		LayoutInflater inflaterDl = LayoutInflater.from(this);
		View layout = inflaterDl.inflate(R.layout.exti_dialog,
				null);
		// 对话框
		Jdialog = new Dialog(this);
		Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		Jdialog.show();

		Jdialog.setContentView(layout);
		TextView sure = (TextView) layout.findViewById(R.id.sureExti);
		TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
		TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
		dialogTitle.setText(str);
		sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
				Jdialog.cancel();
				if(p==1){
					downloadFile(UConstants.URL_DOWN+pat,filePath+odfile);
				}else{
					openFile(new File(filePath+odfile));
				}




			}
		});
		cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Jdialog.dismiss();
			}
		});

	}


	private void downloadFile(final String url, String path) {
		progressDialog = new ProgressDialog(this);
		RequestParams requestParams = new RequestParams(url);
		requestParams.setSaveFilePath(path);
		System.out.println(url);
		x.http().get(requestParams, new Callback.ProgressCallback<File>() {
			@Override
			public void onWaiting() {
			}

			@Override
			public void onStarted() {
			}

			@Override
			public void onLoading(long total, long current, boolean isDownloading) {
				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progressDialog.setMessage("下载中...");
				progressDialog.show();
				progressDialog.setMax((int) total);
				progressDialog.setProgress((int) current);
			}

			@Override
			public void onSuccess(File result) {
				Toast.makeText(DetailsGGaoActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				ex.printStackTrace();
				Toast.makeText(DetailsGGaoActivity.this, "下载失败，文件不存在或网络出错！", Toast.LENGTH_SHORT).show();
				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {
			}
		});
	}



	//获取附件
	public void getFj() {
		Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
		progressDialog = ProgressDialog.show(this, null, "加载中...", true, false);
		RequestParams params = new RequestParams(UConstants.GET_FJLIST);
        params.addBodyParameter("LKind", "OA");
		params.addBodyParameter("TNAME", "ERPGGTZ");
		params.addBodyParameter("XH", emil.getID());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Util.printLog("getDownRoute------------onSuccess-----", result);
				if (result.length() > 0) {
					try {
						JSONObject object = new JSONObject(result);
						boolean success = object.getBoolean("success");
//						String msg = object.getString("msg");
						if (success) {
							Gson gson = new Gson();
							Type lt = new TypeToken<List<Fjian>>() {
							}.getType();
							list = gson.fromJson(object.getString("rows").toString(), lt);
							if (list != null && list.size() > 0) {
								adapter=new FujAdapter(DetailsGGaoActivity.this,list);
								gridView.setAdapter(adapter);
							}


						} else {
							Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();

						}
//
					} catch (JSONException e) {

						Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
				progressDialog.dismiss();

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

				Toast.makeText(x.app(), "获取附件失败！", Toast.LENGTH_LONG).show();
				progressDialog.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {

				Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
				Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
				progressDialog.dismiss();
			}

			@Override
			public void onFinished() {

			}
		});
	}



	//获取邮件详情及阅读邮件
	private void yesRead() {
		RequestParams params = new RequestParams(UConstants.READ_GGAO);
		params.addBodyParameter("LKind", "OA");
		params.addBodyParameter("EmpId", UConstants.EmpId);
		params.addBodyParameter("ID",emil.getID());

		x.http().get(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Util.printLog("getMerchants-----------阅读公告ess-----", result);
				redStr=result;
				handler.sendEmptyMessage(1);
//				if (result.length() > 0) {
//					try {
//						JSONObject object = new JSONObject(result);
//
//						boolean success = object.getBoolean("success");
////
//						if (success) {
//							GGaoActivity.gGaoActivity.setResh();
//						}
////
//					} catch (JSONException e) {
//						e.printStackTrace();
//					}
//				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

//				Toast.makeText(x.app(), "阅读失败！", Toast.LENGTH_LONG).show();

			}

			@Override
			public void onCancelled(CancelledException cex) {

				Toast.makeText(x.app(), "阅读失败", Toast.LENGTH_LONG).show();
				Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");

			}

			@Override
			public void onFinished() {

			}
		});
	}


	/**
	 * 打开文件
	 * @param file
	 */
	private void openFile(File file){

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//设置intent的Action属性
		intent.setAction(Intent.ACTION_VIEW);
		//获取文件file的MIME类型
		String type = getMIMEType(file);
		//设置intent的data和Type属性。
		intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
		//跳转
		startActivity(intent);

	}

	/**
	 * 根据文件后缀名获得对应的MIME类型。
	 * @param file
	 */
	private String getMIMEType(File file) {

		String type="*/*";
		String fName = file.getName();
		//获取后缀名前的分隔符"."在fName中的位置。
		int dotIndex = fName.lastIndexOf(".");
		if(dotIndex < 0){
			return type;
		}
    /* 获取文件的后缀名 */
		String end=fName.substring(dotIndex,fName.length()).toLowerCase();
		if(end=="")return type;
		//在MIME和文件类型的匹配表中找到对应的MIME类型。
		for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？
			if(end.equals(MIME_MapTable[i][0]))
				type = MIME_MapTable[i][1];
		}
		return type;
	}


	private final String[][] MIME_MapTable={
			//{后缀名， MIME类型}
			{".3gp",    "video/3gpp"},
			{".apk",    "application/vnd.android.package-archive"},
			{".asf",    "video/x-ms-asf"},
			{".avi",    "video/x-msvideo"},
			{".bin",    "application/octet-stream"},
			{".bmp",    "image/bmp"},
			{".c",  "text/plain"},
			{".class",  "application/octet-stream"},
			{".conf",   "text/plain"},
			{".cpp",    "text/plain"},
			{".doc",    "application/msword"},
			{".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
			{".xls",    "application/vnd.ms-excel"},
			{".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
			{".exe",    "application/octet-stream"},
			{".gif",    "image/gif"},
			{".gtar",   "application/x-gtar"},
			{".gz", "application/x-gzip"},
			{".h",  "text/plain"},
			{".htm",    "text/html"},
			{".html",   "text/html"},
			{".jar",    "application/java-archive"},
			{".java",   "text/plain"},
			{".jpeg",   "image/jpeg"},
			{".jpg",    "image/jpeg"},
			{".js", "application/x-javascript"},
			{".log",    "text/plain"},
			{".m3u",    "audio/x-mpegurl"},
			{".m4a",    "audio/mp4a-latm"},
			{".m4b",    "audio/mp4a-latm"},
			{".m4p",    "audio/mp4a-latm"},
			{".m4u",    "video/vnd.mpegurl"},
			{".m4v",    "video/x-m4v"},
			{".mov",    "video/quicktime"},
			{".mp2",    "audio/x-mpeg"},
			{".mp3",    "audio/x-mpeg"},
			{".mp4",    "video/mp4"},
			{".mpc",    "application/vnd.mpohun.certificate"},
			{".mpe",    "video/mpeg"},
			{".mpeg",   "video/mpeg"},
			{".mpg",    "video/mpeg"},
			{".mpg4",   "video/mp4"},
			{".mpga",   "audio/mpeg"},
			{".msg",    "application/vnd.ms-outlook"},
			{".ogg",    "audio/ogg"},
			{".pdf",    "application/pdf"},
			{".png",    "image/png"},
			{".pps",    "application/vnd.ms-powerpoint"},
			{".ppt",    "application/vnd.ms-powerpoint"},
			{".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
			{".prop",   "text/plain"},
			{".rc", "text/plain"},
			{".rmvb",   "audio/x-pn-realaudio"},
			{".rtf",    "application/rtf"},
			{".sh", "text/plain"},
			{".tar",    "application/x-tar"},
			{".tgz",    "application/x-compressed"},
			{".txt",    "text/plain"},
			{".wav",    "audio/x-wav"},
			{".wma",    "audio/x-ms-wma"},
			{".wmv",    "audio/x-ms-wmv"},
			{".wps",    "application/vnd.ms-works"},
			{".xml",    "text/plain"},
			{".z",  "application/x-compress"},
			{".zip",    "application/x-zip-compressed"},
			{"",        "*/*"}
	};

}
